console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import YZ from '../commonModule/YZ.js';

import { autoInputAccount } from './options/autoLogin.js';

let baseInfo;

window.onload = function () {
  // 登录填写账号密码
  // if (/\/zjgfdzswj\/main\/index.html/g.test(window.location.pathname)) {
  //   window.postMessage(
  //     {
  //       event: 'getBaseInfo'
  //     },
  //     '*'
  //   );
  // }
  window.postMessage(
    {
      event: 'getBaseInfo'
    },
    '*'
  );

  // 纳税申报表页面
  if (/\/nssb\/sb_nssb.html/g.test(window.location.pathname)) {
    $('#sbxm_zcsb_menu').on('click', 'tbody tr', function () {
      let $tr = $(this),
        $td = $tr.find('td');
      let timeStart = $td.eq(1).text(),
        timeEnd = $td.eq(2).text();
      let typeTaxStr = $td.eq(0).text();

      let taxType = getTaxType(typeTaxStr);

      // 获取申报周期，填充数据
      let timeStr = timeStart + '~' + timeEnd;
      let period = getReportingCycle(timeStr);

      // 渲染填报时间，填报周期
      sendFilter(period, taxType);
    });
  }

  // 小企业现金流量表
  if (/cwbb_xqy_xjllb/g.test(window.location.pathname)) {
    sendFilter({}, 'cash');
    return;
  }
  // 小企业资产负债表
  if (/cwbb_xqy_zcfzb/g.test(window.location.pathname)) {
    sendFilter({}, 'balance');
    return;
  }
  // 小企业利润表
  if (/cwbb_xqy_lrb/g.test(window.location.pathname)) {
    sendFilter({}, 'profit');
  }

  // 按期应申报界面
  if (
    /\/zjgfzjdzswjsbweb\/pages\/sb\/nssb\/sb_nssb.html/g.test(
      window.location.href
    )
  ) {
    $('#zcsb').click();
    setTimeout(function () {
      YZ.captureDataFromPage();
    }, 1000);
  }
};

window.addEventListener(
  'message',
  async function ({ data }) {
    // 只监听来自于content script的信息
    if (data.sender !== 'content-script') {
      return false;
    }
    if (data.event === 'setSaasData') {
      data = data.data;
      let sheet = data.saasData.sheet;
      if (sheet == 'sds' || sheet == 'zzs') {
        fillInput(data, sheet);
      } else {
        fillInput(await transformDataByOpenWeb(data));
      }
    }
    if (data.event === 'getNationData') {
      getNationData();
    }

    if (data.event === 'getBaseInfo') {
      baseInfo = data.data;
      autoInputAccount(baseInfo);
    }

    // 同步申报表种类
    if (data.event === 'syncReportInfo') {
      YZ.startGetReportInfo();
    }
    // 同步申报表
    if (data.event === 'syncReport') {
      YZ.startGetReport();
    }
  },
  false
);
/**
 * 获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '' // 税款所属期止
  };
  window.postMessage(
    {
      event: 'backNationData',
      data: {
        taxInfo: taxInfo
      }
    },
    '*'
  );
}

// function autoInputAccount({ companyInfo }) {
//   $('#loginopen').click();
//   companyInfo = companyInfo || {};
//   $('#username').val(
//     companyInfo.nationalTaxAccount || companyInfo.nationalTaxId
//   );
//   $('#password').val(companyInfo.nationalTaxPass);
// }

function fillInput({ saasData }) {
  let sheet = saasData.sheet;

  let message = '填报成功';
  try {
    let inputData = saasData.data;
    if (sheet == 'sds' || sheet == 'zzs') {
      inputData = delSdsData(inputData.openParams.inputData.data.profit);
    }
    // console.log(saasData);
    // 年报特殊处理
    if (saasData.isYearReport) {
      inputData = YZ.hackYearReportInput(
        inputData,
        saasData.lastYearData,
        saasData.sheet
      );
    }
    for (let key in inputData) {
      let value = Number.parseFloat(inputData[key]).toFixed(2) || '0.00';
      // let value = 1;
      let seletor = `input#${key}`;

      // 汇算清缴 如果id找不到，使用 name 查找
      if (sheet === 'hsqj') {
        if (key.slice(0, 1) === '0') continue;
        if (!document.querySelector(seletor)) {
          seletor = `input[name=${key}]`;
        }
      }

      if ($(seletor).length != 0) {
        if (saasData.isYearReport) {
          $(seletor).val(value);
        } else {
          if (sheet === 'hsqj' && $(seletor).attr('disabled')) continue;
          $(seletor)
            .val(value)
            .trigger('blur');
        }
      }
    }
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage(
    {
      event: 'fillInputDone',
      data: {
        message: message
      }
    },
    '*'
  );
}

function delSdsData(tableData) {
  let sdsData = {};
  // let gsInstitution = getGsInstitution();
  sdsData.yysr = tableData.BNLJJE_1;
  sdsData.yycb = tableData.BNLJJE_2;
  sdsData.lrze = tableData.BNLJJE_30;
  return sdsData;
}

function getTaxType(taxTypeStr) {
  let taxType = 'balance';
  if (taxTypeStr.search('增值税') != -1) {
    taxType = 'zzs';
  } else if (taxTypeStr.search('所得税') != -1) {
    taxType = 'sds';
  } else if (taxTypeStr.search('财务报表') != -1) {
    taxType = 'balance';
  }
  return taxType;
}

/**
 * @param timeStr 时间字符串 2017-04-01~2017-06-30
 * 获取申报周期并且填充数据
 */
function getReportingCycle(timeStr) {
  timeStr = timeStr || '~';
  timeStr = timeStr.split('~');
  let sssq_q = timeStr[0].substr(0, 7);
  let sssq_z = timeStr[1].substr(0, 7);

  return {
    sssq_q: sssq_q,
    sssq_z: sssq_z
  };
}

function sendFilter(period, taxType) {
  let sssq_q = period.sssq_q,
    sssq_z = period.sssq_z;

  if (sssq_q && sssq_z) {
    window.postMessage(
      {
        event: 'setPeriodAndType',
        data: {
          type: taxType,
          startTime: sssq_q,
          endTime: sssq_z
        }
      },
      '*'
    );
  } else if (taxType) {
    window.postMessage(
      {
        event: 'setPeriodAndType',
        data: {
          type: taxType
        }
      },
      '*'
    );
  }
}
